package com.example.demo.interceptor;

import com.example.demo.entity.vo.ResponseResult;
import com.example.demo.enums.StatusCodeEnum;
import com.example.demo.exception.CustomException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * @description：异常捕获处理.
 * @author：lw
 * @since：2023/12/29
 **/
@ControllerAdvice
public class ExceptionInterceptor {
    @ExceptionHandler(Exception.class)    // 捕获系统抛出的异常
    @ResponseBody         // 使得响应数据为json对象
    public ResponseResult<Object> serverError(Exception e){
        return ResponseResult.build(e.getMessage(), StatusCodeEnum.server_error);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)    // 捕获上传文件大小超出限制的异常
    @ResponseBody
    public ResponseResult<Object> uploadError(CustomException e){
        return ResponseResult.build(null,StatusCodeEnum.upload_size_over);
    }

    @ExceptionHandler(CustomException.class)    // 捕获自己手动抛出的ControllerCustomException异常
    @ResponseBody
    public ResponseResult<Object> customError(CustomException e){
        return ResponseResult.build(null,e.getCode(),e.getMessage());
    }
}

